package cn.com.taiji.oospub.wechat.service.impl;

import cn.com.taiji.oospub.wechat.entity.OrderCode;
import cn.com.taiji.oospub.wechat.mapper.OrderCodeMapper;
import cn.com.taiji.oospub.wechat.service.IOrderCodeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 * 订单编号表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-11-30
 */
@Service
public class OrderCodeServiceImpl extends ServiceImpl<OrderCodeMapper, OrderCode> implements IOrderCodeService {
    @Autowired
    private OrderCodeMapper orderCodeMapper;
    @Value("${orderCode}")
    private String orderCode;

    @Override
    public synchronized String[] getNextCodes(String code, String type, int number) {
        //所有序列号从0开始
        SimpleDateFormat YYMMDD = new SimpleDateFormat("yyMMdd");
        Calendar now = Calendar.getInstance();
        String dateTxt = YYMMDD.format(now.getTime());

        QueryWrapper<OrderCode> queryModel = new QueryWrapper<>();
        queryModel.eq("school_code", code);
        queryModel.eq("seq_type", type);
        queryModel.eq("time", dateTxt);
        queryModel.orderByDesc("time");
        List<OrderCode> orderCodes = orderCodeMapper.selectList(queryModel);
        OrderCode curSeq = new OrderCode();
        if (orderCodes.size() > 0) {
            curSeq = orderCodes.get(0);
        } else {
            curSeq.setTime(dateTxt);
            curSeq.setSchoolCode(code);
            curSeq.setSeqType(type);
            curSeq.setSeq(0);
        }

        String[] codes = new String[number];
        for (int i = 0; i < number; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append(curSeq.getSchoolCode()).append("-").append(orderCode);
            sb.append(dateTxt);
            DecimalFormat df = new DecimalFormat("000000");
            sb.append(df.format(curSeq.getSeq() + i + 1));
            codes[i] = sb.toString();
        }
        curSeq.setSeq(curSeq.getSeq() + number);
        if (orderCodeMapper.selectById(curSeq.getId()) != null) {
            orderCodeMapper.updateById(curSeq);
        } else {
            orderCodeMapper.insert(curSeq);
        }

        return codes;
    }
}
